package com.example.tests;

import com.example.model.ItemList;
import com.example.views.MainActivity;
import com.example.views.PostItemActivity;
import com.example.views.ProfileActivity;

import android.app.Instrumentation.ActivityMonitor;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import android.widget.EditText;

public class PostItemTest extends ActivityInstrumentationTestCase2 <PostItemActivity> {

	private PostItemActivity currActivity;
	private ItemList list;
	private Button postItem;
	private Button cancel;
	private EditText name;
	private EditText loc;
	private EditText des;
	
	public PostItemTest(String name) {
		super(PostItemActivity.class);
	}

	protected void setUp() throws Exception {
		setActivityInitialTouchMode(false);
		super.setUp();
		Intent i = createIntent();
		setActivityIntent(i);
		currActivity = getActivity();
		
		list = ItemList.getInstance();
		postItem = (Button) currActivity.findViewById(com.example.R.id.button_post_tem);
		cancel = (Button) currActivity.findViewById(com.example.R.id.button_cancel);	
		
		name = (EditText) currActivity.findViewById(com.example.R.id.editText_item_name);
		loc = (EditText) currActivity.findViewById(com.example.R.id.editText_location_found);
		des = (EditText) currActivity.findViewById(com.example.R.id.editText_description);
	}
	
	public void testPreConditions(){
		currActivity.runOnUiThread(new Runnable(){
			public void run(){
				assertEquals(postItem.getText(), "Post Item");
				assertEquals(cancel.getText(), "Cancel");
			}
		});
	}
	
	public void testCancel(){
		ActivityMonitor activityMonitor = getInstrumentation().addMonitor("ProfileActivity", null, false);
		currActivity.runOnUiThread(new Runnable(){
			public void run(){
				cancel.performClick();
			}});
		ProfileActivity newActivity = (ProfileActivity) getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 5000);
		  // next activity is opened and captured.
		  assertNotNull(newActivity);
		  newActivity.finish();
	}
	
	public void testPostStraightUp(){
		currActivity.runOnUiThread(new Runnable(){
			public void run(){
				fillName("name");
				fillLoc("place");
				fillDes("words");
				postItem.performClick();
			}
		});
		assertTrue(list.contains(list.getItemByName("name")));
	}
	
	private Intent createIntent(){
		Intent i = new Intent();
		i.putExtra(MainActivity.USERNAME,"username");
		return i;
	}
	
	private void fillName(String n){
		name.requestFocus();
		sendKeys(n);
	}
	
	private void fillLoc(String l){
		loc.requestFocus();
		sendKeys(l);
	}
	
	private void fillDes(String d){
		des.requestFocus();
		sendKeys(d);
	}

}
